package com.limanyik.family.common.utils;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 内部通用加密校验（一般用于前端与后端交互签名校验与后端用户密码加密等）
 */
public class InteriorEncryptUtil {

    public static String MD5 = "MD5";

    public static String SHA_256 = "SHA-256";

    public static String SHA_1 = "SHA-1";


    /**
     * 加密函数（注意MessageDigest是线程不安全的）
     *
     * @param msg
     * @param algorithm
     * @return
     */
    @SneakyThrows
    public static String encrypt(String msg, String algorithm) {
        if (StringUtils.isBlank(msg)) {
            return "";
        }
        MessageDigest messageDigest = MessageDigest.getInstance((algorithm = StringUtils.isBlank(algorithm) ? MD5 : algorithm));
        messageDigest.update(msg.getBytes(StandardCharsets.UTF_8));
        byte[] passwordValue = messageDigest.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < passwordValue.length; i++) {
            sb.append(Integer.toHexString((passwordValue[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println(encrypt("测试", MD5));
    }

}
